/**
 * Author: zyf
 * Date: 2020-04-01 14:20
 * Desc: 百度地图
 */
import config from '@/config'
const MAP_KEY = config.BMapKey
import { createScript, getWidowValue } from '@/utils/h5/index'
import GDMap from './map'

const BMap = {
  MAP: null,
  init() {
    const js = {
      src: `https://api.map.baidu.com/api?v=2.0&ak=${MAP_KEY}&s=1&callback=callback`
    }
    createScript(js, 'body').then(() => {
      console.log('百度地图js加载完毕', window.BMap)
    })
  },
  // 获取 Map 对象
  isReady() {
    return getWidowValue('BMap')
  },

  async geolocation() {
    console.log('我启动百度浏览器定位')
    await this.isReady()
    await getWidowValue('Geolocation', window.BMap)
    console.log(window.BMap.Geolocation, '百度Geolocation模块加载完成')

    var location = new window.BMap.Geolocation()
    return new Promise((resolve, reject) => {
      location.getCurrentPosition(async function (r) {
        if (this.getStatus() === window.BMAP_STATUS_SUCCESS) {
          const point = r.point
          console.log(point, '百度坐标')
          const locArr = [point.lng, point.lat]
          GDMap.convertFrom(locArr)
            .then((res) => {
              resolve(res)
            })
            .catch((err) => {
              reject(err)
            })
        } else {
          console.log('浏览器定位出错了' + this.getStatus())
          reject()
          // const defalutAreaInfo = config.areaInfo
          // const data = {
          //     lat: defalutAreaInfo.lat,
          //     lng: defalutAreaInfo.lng
          // }
          // resolve(data)
        }
      })
    })
  }
}
// window.BMap = BMap
window.bb = BMap
export default BMap
